
import { LogoutOutlined, SettingOutlined, UserOutlined } from '@ant-design/icons';
import { useEmotionCss } from '@ant-design/use-emotion-css';
import { Spin } from 'antd';
import type { MenuInfo } from 'rc-menu/lib/interface';
import React, { useCallback } from 'react';
import { flushSync } from 'react-dom';
import HeaderDropdown from "@/component/common/base/HeaderDropdown";
import {useLocation, useNavigate} from "react-router-dom";
import queryString from 'query-string';
import {removeRrefeshToken, removeToken} from "@/utils/tokenCookies";
import {refreshTokenKey} from "@/utils/constants";
import {logOut} from "@/services/api/common";



export type GlobalHeaderRightProps = {
    menu?: boolean;
    children?: React.ReactNode;
};

export const AvatarName = () => {

   // const { currentUser } = initialState || {};
    return <span>flower</span>;
};

export const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({ menu, children }) => {
    let location=useLocation()
    const navigate=useNavigate();
    const { initialState } ={
        initialState:{
            currentUser:{
                name:'ss'
            }
        }
    }

    /**
     * 退出登录，并且将当前的 url 保存
     */
    const loginOut = async () => {
        await logOut();
        removeToken()
        //removeRrefeshToken()
        if (location.pathname !== '/login' ) {
            let searchParams=queryString.stringify({redirect: location.pathname})
            navigate(`/login?${searchParams}`,{
                replace:true
            })
        }
    };
    const actionClassName = useEmotionCss(({ token }) => {
        return {
            display: 'flex',
            height: '48px',
            marginLeft: 'auto',
            overflow: 'hidden',
            alignItems: 'center',
            padding: '0 8px',
            cursor: 'pointer',
            borderRadius: token.borderRadius,
            '&:hover': {
                backgroundColor: token.colorBgTextHover,
            },
        };
    });


    /**
     * 菜单点击事件
     */
    const onMenuClick = useCallback(
        (event: MenuInfo) => {
            const { key } = event;
            if (key === 'logout') {
                flushSync(() => {
                   // setInitialState((s) => ({ ...s, currentUser: undefined }));
                });
                loginOut();
                return;
            }
        },
        [initialState],
    );

    const loading = (
        <span className={actionClassName}>
      <Spin
          size="small"
          style={{
              marginLeft: 8,
              marginRight: 8,
          }}
      />
    </span>
    );

   if (!initialState) {
        return loading;
    }

    const { currentUser } = initialState;

    if (!currentUser || !currentUser.name) {
        return loading;
    }
    const menuItems = [
        ...(menu
            ? [
                {
                    key: 'center',
                    icon: <UserOutlined />,
                    label: '个人中心',
                },
                {
                    key: 'settings',
                    icon: <SettingOutlined />,
                    label: '个人设置',
                },
                {
                    type: 'divider' as const,
                },
            ]
            : []),
        {
            key: 'logout',
            icon: <LogoutOutlined />,
            label: '退出登录',
        },
    ];

    return (

        <HeaderDropdown
            menu={{
                selectedKeys: [],
                onClick: onMenuClick,
                items: menuItems,
            }}
            placement={"bottom"}
        >
            <div>{children}</div>
        </HeaderDropdown>

    );
};
